<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>课程管理</el-breadcrumb-item>
		<el-breadcrumb-item>课程视频管理</el-breadcrumb-item>
	</el-breadcrumb>
	
	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="padding: 15px 0;">
		<el-form-item label="视频名称">
			<el-input v-model="queryInfo.videoName" placeholder="请输入视频名称" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="query">搜索</el-button>
			<el-button type="primary" @click="add">新增视频</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>
	
		<!-- 数据表格 -->
		<el-table ref="multipleTableRef" :data="dataList" style="width: 100%" @selection-change="handleSelectionChange"
			border>
			<el-table-column align="center" type="selection" width="50" />
			<el-table-column align="center" property="id" label="ID" width="55" >
				<template #default="scope">
				      <!-- scope.$index 是当前行的索引（从 0 开始） -->
				      {{ scope.$index + 1 }}
				</template>
			</el-table-column>
			<el-table-column align="center" property="videoName" label="视频名称" />
			<el-table-column align="center" property="videoView" label="视频图片">
				<template #default="scope">
					<video :src="'http://localhost:8080'+ scope.row.videoUrl"  controls height="200" width="100%" >

					</video>
				</template>
			</el-table-column>
			<el-table-column property="videoTime" label="视频时长" >
				<template #default="scoped">
						{{ formatTimes(scoped.row.videoTime) }}
				</template>
			</el-table-column>
			
			<el-table-column property="course.courseName" label="所属课程" />
			<el-table-column fixed="right" label="操作" width="220">
				<template #default="scope">
					<el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
					<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	
	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />
	
	<!-- 新增和修改对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="addOrUpdateVideo" label-width="100">
			<el-form-item label="视频名称">
				<el-input v-model="addOrUpdateVideo.videoName" autocomplete="off" placeholder="请输入视频名称"></el-input>
			</el-form-item>
			<el-form-item label="视频上传">
				  <el-upload
					v-model:file-list="fileList" 
					action="http://localhost:8080/upload"
					list-type="picture-card"
					limit="1"
					:on-preview="handlePictureCardPreview"
					:on-success="handleAvatarSuccess"
					:on-remove="handleRemove"
				  >
					<el-icon><Plus /></el-icon>
				  </el-upload>

				  <el-dialog v-model="dialogVideoVisible" title="视频预览" width="60%">
				    <video style="width: 100%; height: auto;" :src="dialogVideoUrl" controls />
				  </el-dialog>
			</el-form-item>
		
				<el-form-item label="课程名称">
					<el-select v-model="addOrUpdateVideo.courseId" placeholder="请输入课程名称"  style="width: 240px">
						<el-option
						v-for="item in options"
						:key="item.value"
						:label="item.courseName"
						:value="item.id"
						/>
					</el-select>
				</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
	
</template>

<script setup>
	import { getCurrentInstance,reactive} from 'vue';
	import {ref,onMounted} from 'vue';
	import {ElMessage,ElMessageBox} from 'element-plus';
	import {Plus} from '@element-plus/icons-vue';
	import { cloneDeep } from 'lodash-es';
	
	//封装请求路径的函数
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	//记录数
	const total = ref(0);
	
	//文件上传时展示图片路径
	const dialogVideoUrl = ref('')
	//文件上传时图片显示
	const dialogVideoVisible = ref(false)
	//文件长传列表
	const fileList = ref([])
	//课程类型
	const options=ref([])

	/* 查询信息对象 */
	const queryInfo = reactive({
		id:"",
		videoName:"",
		videoView:"",
		videoTime:"",
		courseName:"",
		courseId:0,
		pageSize:10,
		pageNum:1
	})
	//当前页数据
	const dataList = ref([])
	//存储复选数据
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}
	
	const query = () => {
		axios.get(`courseVideo/page`, {
				params: queryInfo
			})
			.then((resp) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list;
					total.value = resp.data.total;
				} else {
					ElMessage.error(resp.message)
				}
	
			})
	}
	//查询分类
	const queryTypeList=()=>{
		axios.get(`course/select`).then((resp)=>{
			if (resp.code === 200) {
				options.value=resp.data;
				console.log(resp.data);
			}
		})
	}
	
	//组件加载完毕，查询数据
	onMounted(() => {
		query();
		queryTypeList();
	});
	//每页显示条目数改变
	const handleSizeChange = (val) => {
		queryInfo.pageSize = val;
		query();
	};
	//页码改变
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val;
		query();
	};
	
	const title = ref('新增课程视频')
	const dialogFormVisible = ref(false)
	//新增修改数据集
	const addOrUpdateVideo = ref({
			id:"",
			videoName:"",
			videoUrl:"",
			videoTime:"",
			courseId:null,
	})
	
	//当点击关闭按钮 或 取消按钮的时候，重置表单
	const cancle = () => {
		console.log('你点击了取消按钮');
		addOrUpdateVideo.value = {
			id:"",
			videoName:"",
			videoUrl:"",
			videoTime:"",
			courseId:null,
		}
		// 清空文件列表
		fileList.value = []
		dialogFormVisible.value = false
	}
	
	//确定按钮
	const confirm = () => {
		console.log('你点击了确定按钮');
		if (addOrUpdateVideo.value.id) { //数据存在id，修改
			axios.put('courseVideo/update', addOrUpdateVideo.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
					dialogFormVisible.value = false
				})
		} else { //新增
			axios.post('courseVideo/add', addOrUpdateVideo.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
					dialogFormVisible.value = false
				})
		}
	}
	
	//点击新增按钮的时候，弹出对话框
	const add = () => {
		// 清空文件列表
		fileList.value = []
		dialogFormVisible.value = true
	}
	//编辑
	const edit = (row) => {
		console.log(row);
		
		title.value = '编辑课程视频'
		dialogFormVisible.value = true
		addOrUpdateVideo.value = cloneDeep(row)
		
		// 清空之前的文件列表
		fileList.value = []
		
		// 如果有视频URL，则添加到文件列表中用于回显
		var listView = addOrUpdateVideo.value.videoUrl;
		if(listView){
			fileList.value.push({
				name: listView.substr(listView.lastIndexOf('/') + 1),
				url: 'http://localhost:8080' + listView,
			})
		}
	}
	
	//单个删除
	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', 'Warning', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			axios.delete(`courseVideo/delete/${id}`)
				.then(resp => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
					dialogFormVisible.value = false
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
	
	//批量删除
	const batchRemove = () => {
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', 'Warning', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			axios.delete('courseVideo/delete', {
					params: {
						ids: multipleSelection.value.join(',')
					}
				})
				.then(resp => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					query();
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}

	//图片上传成功的回调函数
	const handleAvatarSuccess=(resp)=>{
		console.log('上传成功:', resp);
		if (resp.code === 200) {
			addOrUpdateVideo.value.videoUrl = resp.data;
			ElMessage.success('视频上传成功');
		} else {
			ElMessage.error(resp.message || '上传失败');
		}
	}



	//用来计算毫秒值转换为时分秒
	const formatTimes =(ms)=>{
		console.log(ms);
		
		if (ms === null || ms === undefined) return '00:00:00'

		
      const totalSeconds = Math.floor(ms / 1000)
      const hours = Math.floor(totalSeconds / 3600)
      const minutes = Math.floor((totalSeconds % 3600) / 60)
      const seconds = totalSeconds % 60
      
      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        seconds.toString().padStart(2, '0')
      ].join(':')
	}
	
</script>

<style scoped>
	.el-pagination {
		margin-top: 15px;
	}
	.el-breadcrumb {
		height: 20px;
		font-size: 15px;
		border-bottom: 1px solid #eee;
		padding-bottom: 15px;
	}
	
	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}
	
	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}
	
</style>